package com.sheyu.mall.product.service.attr.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.sheyu.common.constant.ProductConstant;
import com.sheyu.mall.product.dao.attr.AttrAttrgroupRelationDao;
import com.sheyu.mall.product.dao.attr.AttrGroupDao;
import com.sheyu.mall.product.dao.category.CategoryDao;
import com.sheyu.mall.product.entity.attr.AttrAttrgroupRelationEntity;
import com.sheyu.mall.product.entity.attr.AttrGroupEntity;
import com.sheyu.mall.product.entity.category.CategoryEntity;
import com.sheyu.mall.product.service.category.CategoryService;
import com.sheyu.mall.product.service.attr.vo.AttrGroupRelationVo;
import com.sheyu.mall.product.vo.AttrGroupVo;
import com.sheyu.mall.product.vo.AttrVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sheyu.common.utils.PageUtils;
import com.sheyu.common.utils.Query;

import com.sheyu.mall.product.dao.attr.AttrDao;
import com.sheyu.mall.product.entity.attr.AttrEntity;
import com.sheyu.mall.product.service.attr.AttrService;
import org.springframework.transaction.annotation.Transactional;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    AttrAttrgroupRelationDao relationDao;

    @Autowired
    AttrGroupDao attrGroupDao;

    @Autowired
    CategoryDao categoryDao;

    @Autowired
    CategoryService categoryService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveAttrVo(AttrVo attrVo) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrVo,attrEntity);
        this.save(attrEntity);
        if (attrVo.getAttrType().equals(ProductConstant.AttrEnum.ATTR_BASE_ENUM.getCode())) {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrGroupId(attrVo.getAttrGroupId());
            attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId());
            relationDao.insert(attrAttrgroupRelationEntity);
        }

    }

    @Override
    public PageUtils queryPageBycategoryId(Map<String, Object> params, Long catelogId, String attrType) {
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>().eq("attr_type","base".equalsIgnoreCase(attrType)?
                ProductConstant.AttrEnum.ATTR_BASE_ENUM.getCode() :ProductConstant.AttrEnum.ATTR_SALE_ENUM.getCode());
        if (catelogId!=0){
            queryWrapper.eq("catelog_id",catelogId);
        }
        String key = (String) params.get("key");
        if(StringUtils.isNotBlank(key)){
            queryWrapper.and((obj)->{
                obj.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper
        );
        PageUtils pageUtils = new PageUtils(page);
        List<AttrEntity> records = page.getRecords();
        List<AttrGroupVo> attrGroupVos = records.stream().map((attrEntity) -> {
            AttrGroupVo attrGroupVo = new AttrGroupVo();
            BeanUtils.copyProperties(attrEntity,attrGroupVo);
            AttrAttrgroupRelationEntity relationEntity = relationDao
                    .selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",attrEntity.getAttrId()));
            if(null != relationEntity && relationEntity.getAttrGroupId() != null&&"base".equalsIgnoreCase(attrType)) {
                Long groupId = relationEntity.getAttrGroupId();
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(groupId);
                attrGroupVo.setGroupName(attrGroupEntity.getAttrGroupName());
            }

            CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
            if (categoryEntity!=null) {
                attrGroupVo.setCatelogName(categoryEntity.getName());
            }

            return attrGroupVo;
        }).collect(Collectors.toList());
        pageUtils.setList(attrGroupVos);
        return pageUtils;
    }

    @Override
    public AttrGroupVo getAttrInfo(Long attrId) {
        /**
        AttrEntity attrEntity = this.getById(attrId);
        AttrGroupVo attrGroupVo = new AttrGroupVo();
        BeanUtils.copyProperties(attrEntity,attrGroupVo);
        AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = relationDao
                .selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",attrEntity.getAttrId()));
        if(attrAttrgroupRelationEntity!=null) {
            attrGroupVo.setAttrGroupId(attrAttrgroupRelationEntity.getAttrGroupId());
            AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrAttrgroupRelationEntity.getAttrGroupId());
            attrGroupVo.setGroupName(attrGroupEntity.getAttrGroupName());
        }
        if (attrEntity.getCatelogId()!=null) {
            Long[] categoryPaths = categoryService.categoryPath(attrEntity.getCatelogId());
            attrGroupVo.setCateglogPath(categoryPaths);
            CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
            if (categoryEntity!=null) {
                attrGroupVo.setCatelogName(categoryEntity.getName());
            }
        }
        return attrGroupVo;*/
        //查询详细信息
        AttrEntity attrEntity = this.getById(attrId);

        //查询分组信息
        AttrGroupVo respVo = new AttrGroupVo();
        BeanUtils.copyProperties(attrEntity,respVo);

        //判断是否是基本类型
        //1、设置分组信息
        if (attrEntity.getAttrType().equals(ProductConstant.AttrEnum.ATTR_BASE_ENUM.getCode())) {
            AttrAttrgroupRelationEntity relationEntity = relationDao.selectOne
                    (new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
            if (relationEntity != null) {
                respVo.setAttrGroupId(relationEntity.getAttrGroupId());
                //获取分组名称
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
                if (attrGroupEntity != null) {
                    respVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
        }
        //2、设置分类信息
        Long catelogId = attrEntity.getCatelogId();
        Long[] catelogPath = categoryService.categoryPath(catelogId);

        respVo.setCatelogPath(catelogPath);
        CategoryEntity categoryEntity = categoryDao.selectById(catelogId);
        if (categoryEntity != null) {
            respVo.setCatelogName(categoryEntity.getName());
        }

        return respVo;
    }
    @Transactional
    @Override
    public void updateAttrVo(AttrVo attrVo) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrVo,attrEntity);
        this.updateById(attrEntity);
        if (attrVo.getAttrType().equals(ProductConstant.AttrEnum.ATTR_BASE_ENUM.getCode())) {
            Long attrId = attrEntity.getAttrId();
            Long attrGroupId = attrVo.getAttrGroupId();
            UpdateWrapper updateWrapper = new UpdateWrapper<>();
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity
                    = new AttrAttrgroupRelationEntity();
            AttrAttrgroupRelationEntity selectOneByAttrAttrgroupRelationEntity =
                    relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq(
                            "attr_id", attrId));
            if (selectOneByAttrAttrgroupRelationEntity != null) {

                attrAttrgroupRelationEntity.setAttrId(attrId);
                attrAttrgroupRelationEntity.setAttrGroupId(attrGroupId);
                updateWrapper.eq("attr_id", attrEntity.getAttrId());
                relationDao.update(attrAttrgroupRelationEntity, updateWrapper);
            } else {
                attrAttrgroupRelationEntity.setAttrGroupId(attrGroupId);
                attrAttrgroupRelationEntity.setAttrId(attrId);
                relationDao.insert(attrAttrgroupRelationEntity);

            }
        }
    }

    @Override
    public void queryPageBycategoryIdTest(Long catelogId) {
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>().eq("attr_type","base".equalsIgnoreCase("base")?1:0);
        if (catelogId!=0){
            queryWrapper.eq("category_id",catelogId);
        }

        System.out.println(this.getMap(queryWrapper));
//        String key = (String) params.get("key");
//        if(StringUtils.isNotBlank(key)){
//            queryWrapper.and((obj)->{
//                obj.eq("attr_id",key).or().like("attr_name",key);
//            });
//        }
//        IPage<AttrEntity> page = this.page(
//                new Query<AttrEntity>().getPage(params),
//                queryWrapper
//        );

    }

    @Override
    public void deleteRealtion(AttrGroupRelationVo[] attrGroupRelationVo) {

        relationDao.deleteBatchRelationIds( Arrays.asList(attrGroupRelationVo));
    }

    @Override
    public PageUtils queryAttrByNoRelationAttrgroupId(Map<String, Object> params, Long attrgroupId) {
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);
        Long catelogId = attrGroupEntity.getCatelogId();

        /**
        List<AttrGroupEntity> groupEntities = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id",catelogId));

        //获取分类对应的属性分组
        List<Long> groupIds = groupEntities.stream().map((obj)->{
            return obj.getAttrGroupId();
        }).collect(Collectors.toList());

        List<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntities = relationDao.
                selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", groupIds));
        List<Long> attrIds = attrAttrgroupRelationEntities.stream().map((obj)->{
            return obj.getAttrId();
        }).collect(Collectors.toList());
        **/

        List<Long> attrIds = attrGroupDao.joinCatelogAndAttrGroup(catelogId);

        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("catelog_id",catelogId).eq("attr_type",ProductConstant.AttrEnum.ATTR_BASE_ENUM.getCode());
        if (attrIds!=null && attrIds.size()>0) {
            wrapper.notIn("attr_id", attrIds);
        }
        String key = (String)params.get("key");
        if (StringUtils.isNotBlank(key)){
            wrapper.and((obj ->{
                obj.eq("attr_id",key).or().like("attr_name",key);
            }));
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );
        return new PageUtils(page);
    }

    @Override
    public List<Long> selectSearchAttrs(List<Long> attrIds) {
        List<Long> searchAttrIds = this.baseMapper.selectSearchAttrs(attrIds);
        return searchAttrIds;
    }

}
